import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const user_time = 'user_time'
const useValidTime = 1 * 60 * 60 * 1000;
const store = new Vuex.Store({
    state: {
        // 存储token
        Authorization: localStorage.getItem('Authorization') ? localStorage.getItem('Authorization') : '',


        user: {
            username: window.localStorage.getItem('user' || '[]') == null ? '' : JSON.parse(window.localStorage.getItem('user' || '[]')).username

        },
    },
    getters: {

        Authorization: function (state) {

            if (!state.Authorization) {
                let Authorization2 = JSON.parse(localStorage.getItem('Authorization'));
                if (Authorization2) {
                    //获取用户登录时间
                    let strtime = localStorage.getItem(user_time);
                    console.log(strtime);
                    if (strtime) {
                        //计算过期时间
                        let vaildtime = Number(strtime) + useValidTime
                        let timespan = Date.parse(new Date())

                        if (timespan < vaildtime) {

                            console.log("token未过期")
                            state.Authorization = Authorization2;
                            return state.Authorization;
                        }

                    }
                    console.log("token已过期")
                    localStorage.setItem('Authorization', null);
                }


            }
            return state.Authorization;

        }

    },
    mutations: {
        // 修改token，并将token存入localStorage
        changeLogin(state, token) {
            // console.log(token);
            state.Authorization = token.Authorization;
            localStorage.setItem('Authorization', token.Authorization);
            let timespan = Date.parse(new Date())
            localStorage.setItem(user_time, timespan);
        },


        changeLogin2(state, user) {

            state.user = user
            window.localStorage.setItem('user', JSON.stringify(user))
        },


    }
});

export default store;